# -*- coding: utf-8 -*-
"""
Created on Fri Jun 20 11:59:35 2014

@author: Adrien
"""

import csv
import xlrd
import DatabaseHandlerInterface as DBHi
import Tkinter
import ttk
import tkFileDialog
import DataModel as Model

class CancerGeneCensus(DBHi.DatabasePluginInterface):
    
     def __init__(self):
        self._options={'path':''}
        self._data=None
        self._headers=[]
        self._diseases=[]
     
     def setConfigDoneFunction(self,func):
        self.configDoneFunction=func
    
     def getData(self):
         if self._data==None:
             self.readFile()
         return self.data
     
     def setDiseasesList(self,diseases):
         self._diseases=diseases
         
     def readFile(self):
        filePath=self._options['path']
        try:
         	book= xlrd.open_workbook(filePath)
        except:
		raise Exception('cannot open file')
        else:
            self.data={'genes':[],'fusions':[]}
            abbreviationSheet=book.sheet_by_name('Abbreviations')
            listSheet = book.sheet_by_name('List')
            diseases =[]
            diseases += self._diseases
            num=0
            for rownum in range(abbreviationSheet.nrows):
                myRow = abbreviationSheet.row_values(rownum)
                if num ==0:
                    pass
                else:                  
                    for disease in self._diseases:
                        if myRow[1].find(disease)!=-1 and myRow[0] not in diseases:
                            diseases.append(myRow[0])
                num+=1
            num=0
            for rownum in range(listSheet.nrows):
                myRow = listSheet.row_values(rownum)
                if num ==0:
                    self._headers = myRow
                else:
                    disease =""
                    if myRow[7]!="":
                        disease+=myRow[7]+ ","
                    if myRow[8]!="":
                        disease+=myRow[8]+ ","
                    if myRow[9]!="":
                        disease+=myRow[9]+ ","
                    if myRow[15]!="":
                        disease+=myRow[15]
                    geneA =Model.Gene(myRow[0],function=myRow[1],chromosome=myRow[3],disease=disease,locus=myRow[4])
                    if geneA not in self.data['genes']:
                        self.data['genes'].append(geneA)
                    parternsStr=myRow[13].strip()
                    if parternsStr:
                        partners = parternsStr.split(",")
                        for partner in partners:
                            fusion = Model.Fusion(myRow[0],partner.strip(),breakpointA="", strandA="", fusionDirectionA="",breakpointB="", strandB="", fusionDirectionB="",notes="")
                            if fusion not in self.data['fusions']:
                                self.data['fusions'].append(fusion)
                num+=1
        return self._data
        
     def setData(self,data):
         self._data=data
    
     def getOptionPanel(self,parent):
         self.v = Tkinter.StringVar()
         self.y = Tkinter.StringVar()
         self.y.set(self._options['path'])
         self.optionPanelIn=ttk.Frame(parent)
         title = ttk.Label(self.optionPanelIn,text="Cancer gene census")
         label0 = ttk.Label(self.optionPanelIn,text="Database file path:")
         ent0 = ttk.Entry(self.optionPanelIn,textvariable=self.y)
         
         browseBtn = ttk.Button(self.optionPanelIn, text="Browse...",command=self.browse)
         selectBtn = ttk.Button(self.optionPanelIn, text="OK",command=self.select)
         abortBtn = ttk.Button(self.optionPanelIn, text="Cancel",command=self.optionPanelIn.destroy)
         
         title.pack()
         label0.pack()
         ent0.pack(fill=Tkinter.X)
         browseBtn.pack()
         selectBtn.pack(fill=Tkinter.X)
         abortBtn.pack(fill=Tkinter.X)
         
         self.optionPanelIn.pack(side="top", fill="both", expand=1)
         return self.optionPanelIn
    
     def browse(self):
        dir_opt = options = {}
        options['initialdir'] = self.v.get()
        options['title'] = 'Select cancer_gene_census.xls:'
        options['parent'] = self.optionPanelIn
        directory=tkFileDialog.askopenfilename(**dir_opt)
        if directory != None and directory!="":
            self.y.set(directory)
         
     def select(self):
         self._options['path']=self.y.get()
         self.configDoneFunction()
             
     def setConfig(self,options):
         self._options=options
     
     def getConfig(self):
         return self._options




def openFile(path,mode):
     try:
         myFileobj = open(path,mode)
         return myFileobj
     except IOError:
             raise Exception('cannot open file')  
    